package com.faiz.algorithm;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Data
public class BinaryTree {
    protected int value;
    protected BinaryTree left;
    protected BinaryTree right;

    public BinaryTree(int value) {
        this.value = value;
    }

    public static BinaryTree of(Integer[] array, int index) {
        BinaryTree root = null;
        if (index < array.length) {
            Integer value = array[index];
            if (value != null) {
                root = new BinaryTree(value);
                root.setLeft(of(array, 2 * index + 1));
                root.setRight(of(array, 2 * index + 2));
            }
        }
        return root;
    }

    @Override
    public String toString() {
        String left = (getLeft() != null ? String.valueOf(getLeft().value) : "null");
        String right =  (getRight() != null ? String.valueOf(getRight().value) : "null");
        return "BinaryTree{" +
                "value=" + value +
                ", left=" + left +
                ", right=" + right +
                '}';
    }
}
